// 1.引入http模块
var http = require('http')
var url = require('url')
var fs = require('fs')
var queryString = require('querystring')
var timeYear = new Date().getFullYear()
var timeMonth = new Date().getMonth()
var timeDay = new Date().getDay()
var timeHours = new Date().getHours()
var timeMinutes = new Date().getMinutes()
var timeSeconds = new Date().getSeconds()
var timeDate = `${timeYear}-${timeMonth}-${timeDay} ${timeHours}:${timeMinutes}:${timeSeconds}`
var testData = [
    { name: '张三', content: '我是张三，你们好啊', create_date: '2017-11-13 10:22:55' },
    { name: '张四', content: '我是张四，你们好啊', create_date: '2017-11-13 10:22:55' },
    { name: '张五', content: '我是张五，你们好啊', create_date: '2017-11-13 10:22:55' },
    { name: '张路', content: '我是张路，你们好啊', create_date: '2017-11-13 10:22:55' },
]
// 2.创建web服务器
var server = http.createServer()
// 3.监听请求
server.on('request', (req, res) => {
    // 获取当前请求地址
    var baseUrl = req.url
    // 请求加载留言板列表
    if (baseUrl === '/') {
        fs.readFile('./views/index.html', 'utf8', (err, data) => {
            if (err) res.end('404 Not Found')
            var html = ""
            testData.forEach(v => {
                html += `<li class="list_item">
                <div class="list_user">${v.name}</div>
                <div class="list_content">${v.content}</div>
                <div class="list_date">${v.create_date}</div>
              </li>`
            })
            // 替换页面占位数据
            var finalData = data.replace('^_^', html)
            readFileCommon(err, finalData, res, true)
        })
    } else if (baseUrl === '/add') {
        fs.readFile('./views/add.html', 'utf8', (err, data) => {
            if (err) res.end('404 Not Found')

            readFileCommon(err, data, res, true)
        })
    } else if (baseUrl.indexOf('/public') > -1) {
        // 检测静态资源并响应
        fs.readFile('./' + baseUrl, 'utf8', (err, data) => {
            if (err) res.end('404 Not Found')
            readFileCommon(err, data, res, false)
        })
    } else if (baseUrl.indexOf('/doadd') > -1) {
        // 添加留言-表单提交
        if (req.method === 'POST') {
            // post提交数据大，分片获取
            // data-数据传输中；end-数据传输完毕；
            var postData = ""
            req.on('data', (chunk) => {
                postData += chunk
            })
            req.on('end', () => {
                // 1.接收数据
                const paramObj = queryString.parse(postData)
                console.log(paramObj, timeDate)
                var msg = { name: paramObj.name, content: paramObj.content, create_date: timeDate }
                // 2.入库，添加到文件中
                testData.push(msg)
                // 3.跳转
                res.statusCode = 302 //站内跳转
                res.setHeader('Location', '/')
                res.end()
            })

        } else {
            // 1.接收数据
            const paramObj = url.parse(req.url, true).query
            console.log(paramObj, timeDate)
            var msg = { name: paramObj.name, content: paramObj.content, create_date: timeDate }
            // 2.入库，添加到文件中
            testData.push(msg)
            // 3.跳转
            res.statusCode = 302 //站内跳转
            res.setHeader('Location', '/')
            res.end()
        }

    } else {
        // 404
        fs.readFile('./views/404.html', 'utf8', (err, data) => {
            if (err) res.end('404 Not Found')
            // res.setHeader('Content-type', 'text/html;charset=utf-8')
            // res.write(data)
            // res.end()
            readFileCommon(err, data, res, true)
        })
    }
})
// 4.启动服务
server.listen(8080, () => {
    console.log('服务启动成功,访问：http://localhost:8080')
})

var readFileCommon = (err, data, res, type) => {
    if (type) {
        // html文件-自定义头部
        res.setHeader('Content-type', 'text/html;charset=utf-8')
    }
    res.write(data)
    res.end()
}